import { getChannelList,deleteChannel } from '@/api/Member/index.js'
import { useConfirm } from '@/hooks'

const seachTableRef = ref(null)
export const useCommonData = (props) => {
  return {
    seachTableRef
  }
}
export const useCurd = (props) => {
  // 表格数据
  const tableLoading = ref(false)
  const totalPage = ref(0)
  const tableData = ref([])

  // 搜索
  const handlerSearch = async (data) => {
    try{
      tableLoading.value = true
      const res = await getChannelList(data)
      tableData.value = res
      totalPage.value = +res.length
    }finally{
      tableLoading.value = false
    }
  }

  // 弹窗相关
  const dialogData = ref({})
  const showEditDialog = ref(false)
  const closeEditDialog = () => {
    showEditDialog.value = false
  }
  const openEditDialog = (row = {}) => {
    console.log('编辑',row)
    dialogData.value = row
    showEditDialog.value = true
  }

  /**表格配置start */
  const btnLefts = [
    {
      label:'新增',
      type:'primary',
      show:()=>true,
      img:new URL("@/assets/icon/btn-add.png",import.meta.url),
      click:()=>{
        openEditDialog()
      }
    },
  ]
  const btnRights = []
  const tableConfig = ref([
    {
      label:'渠道名称',
      prop:'sourceChannel',
      width: 1000,
      type:'slot',
      slotName:'sourceChannel'
    },
    {
      type: "action",
      label:'操作',
      prop:'name',
      fixed: "right",
      btns:[
        {
          label:()=>'编辑',
          type:'success',
          show:(row)=>row.sourceChannelType === 1,
          click:(row)=>{
            openEditDialog(row)
          }
        },
        {
          label:()=>'删除',
          type:'danger',
          show:(row)=>row.sourceChannelType === 1,
          click:(row)=>{
            ElMessageBox.confirm(`确定删除【${row.sourceChannel}】渠道?`, '提示', {
              type: 'error',
              beforeClose: async (action, instance, done) => {
                const res = await useConfirm(action, instance, done,deleteChannel, row.id)
                if(res){
                  ElMessage.success('删除成功')
                  seachTableRef.value.handlerSearch()
                }
              }
            })
          }
        }
      ]
    }
  ])
  const tableForms = ref([])
  /**表格配置end */

  return {
    tableLoading,
    totalPage,
    tableData,
    btnLefts,
    btnRights,
    tableConfig,
    tableForms,
    handlerSearch,
    showEditDialog,
    dialogData,
    closeEditDialog
  }
}